package com.ad.platform.service.impl;

import com.ad.payload.dto.PfCategoryDto;
import com.ad.payload.dto.trade.CategorySearch;
import com.ad.payload.dto.trade.TradeSubAddDto;
import com.ad.payload.dto.trade.TradeSubDto;
import com.ad.payload.dto.trade.TradeSubEditDto;
import com.ad.payload.model.IdDto;
import com.ad.payload.model.PageView;
import com.ad.payload.vo.PfCategoryVo;
import com.ad.payload.vo.trade.*;
import com.ad.platform.common.constant.Const;
import com.ad.platform.common.utils.BeanUtil;
import com.ad.platform.enums.LevelEnum;
import com.ad.platform.enums.StatusEnum;
import com.ad.platform.mapper.CategoryDisplayMapper;
import com.ad.platform.mapper.PfCategoryMapper;
import com.ad.platform.mapper.PfCategorySubMapper;
import com.ad.platform.model.CategoryDisplay;
import com.ad.platform.model.PfCategory;
import com.ad.platform.model.PfCategorySub;
import com.ad.platform.service.IPfCategoryService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author rclia
 * @since 2021-03-10
 */
@Service
@Slf4j
public class PfCategoryServiceImpl extends ServiceImpl<PfCategoryMapper, PfCategory> implements IPfCategoryService {

    @Autowired
    private PfCategoryMapper pfCategoryMapper;

    @Autowired
    private PfCategorySubMapper pfCategorySubMapper;

    @Autowired
    private CategoryDisplayMapper categoryDisplayMapper;

    @Override
    public PageView<PfCategoryVo> selectPage(long pageNo, long pageSize) {
        IPage<PfCategory> page = new Page(pageNo, pageSize);
        IPage<PfCategory> pfCategoryIPage = pfCategoryMapper.selectPage(page, null);

        // 通过Ipage实例化pageView
        PageView pageView = new PageView(pfCategoryIPage);

        // 实体转vo
        List<PfCategoryVo> rtnList = new ArrayList();
        pfCategoryIPage.getRecords().forEach(item -> {
            PfCategoryVo vo = new PfCategoryVo();
            BeanUtil.copyProperties(item, vo);
            rtnList.add(vo);
        });

        pageView.setPageList(rtnList);
        return pageView;
    }

    @Override
    public boolean saveOrUpdate(@Valid PfCategoryDto pfCategoryDto) {
        log.info("入参 ============================================ " + JSON.toJSONString(pfCategoryDto));
        PfCategory category = new PfCategory();
        BeanUtils.copyProperties(pfCategoryDto,category);

        if(pfCategoryDto.getId() == null){
            //新增
            pfCategoryMapper.insert(category);
        } else {
            //更新
            pfCategoryMapper.updateById(category);
        }

        return true;
    }

    @Override
    public boolean removeById(@NotNull(message = "id不能为空") Long id) {
        log.info("入参 ============================================  " + id);
        pfCategoryMapper.deleteById(id);
        return true;
    }

    @Override
    public List<PfCategoryVo> selectListForMini() {

        Map<String, String> params = new HashMap<String, String>();
        params.put("status",StatusEnum.ENABLED.getValue());
        List<PfCategory> categoryList =  pfCategoryMapper.selectLimit20(params);

        // 实体转vo
        List<PfCategoryVo> rtnList = new ArrayList();
        categoryList.forEach(item -> {
            PfCategoryVo vo = new PfCategoryVo();
            BeanUtil.copyProperties(item, vo);
            rtnList.add(vo);
        });

        return rtnList;

    }


    /**
     * 根据行业id查询子行业列表
     *
     * @param tradeSubDto
     */
    @Override
    public PageView<TradeVo> pageListSubTradeVo(TradeSubDto tradeSubDto) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("id");
        queryWrapper.eq("trade_id", tradeSubDto.getTradeId());
        IPage iPage =
                pfCategorySubMapper.selectPage(new Page(tradeSubDto.getPageNo(), tradeSubDto.getPageSize()), queryWrapper);
        PageView pageView = new PageView(iPage);
        List pageList = pageView.getPageList();

        // 查询上级类目

        PfCategory pfCategory = pfCategoryMapper.selectById(tradeSubDto.getTradeId());

        String categoryName = null;
        if(pfCategory != null){
            categoryName = pfCategory.getCategoryName();
        }

        List<TradeVo> rtnList = new ArrayList<>();

        for (Object item : pageList) {
            TradeVo tradeVo = new TradeVo();
            PfCategorySub sub = (PfCategorySub) item;
            BeanUtil.copyProperties(item, tradeVo);
            tradeVo.setName(sub.getSubName());
            tradeVo.setCategoryId(String.valueOf(tradeSubDto.getTradeId()));
            tradeVo.setCategoryName(categoryName);
            rtnList.add(tradeVo);
        }

        pageView.setPageList(rtnList);
        return pageView;
    }

    /**
     * 添加子行业
     *
     * @param tradeSubAddDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addSubTrade(TradeSubAddDto tradeSubAddDto) {
        PfCategorySub pf = new PfCategorySub();
        BeanUtil.copyProperties(tradeSubAddDto, pf);
        pfCategorySubMapper.insert(pf);
        return pf.getId();
    }

    /**
     * 编辑子行业
     *
     * @param tradeSubEditDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long editSubTrade(TradeSubEditDto tradeSubEditDto) {
        PfCategorySub pf = new PfCategorySub();
        BeanUtil.copyProperties(tradeSubEditDto, pf);
        pfCategorySubMapper.updateById(pf);
        return tradeSubEditDto.getId();
    }

    /**
     * 删除子行业
     *
     * @param idDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long deleteSubTrade(IdDto idDto) {
        pfCategorySubMapper.deleteById(idDto.getId());
        return idDto.getId();
    }

    /**
     * 查询行业左侧
     *
     * @param categorySearch
     */
    @Override
    public List<CategoryLeftVo> queryCategoryLeftVo(CategorySearch categorySearch) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByAsc("id");
        List<PfCategory> list = pfCategoryMapper.selectList(queryWrapper);

        List<CategoryLeftVo> rtnList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            PfCategory item = list.get(i);
            CategoryLeftVo vo = new CategoryLeftVo();
            vo.setId(item.getId());
            vo.setName(item.getCategoryName());
            vo.setTabActive(i);
            rtnList.add(vo);
        }
        return rtnList;
    }

    /**
     * 查询行业右侧
     *
     * @param categorySearch
     */
    @Override
    public List<List<CategoryRightFirstVo>> queryCategoryRightVo(CategorySearch categorySearch) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByAsc("id");
        List<PfCategory> list = pfCategoryMapper.selectList(queryWrapper);

        List<List<CategoryRightFirstVo>> rtnList = new ArrayList<>();
        list.forEach(item -> {
            // 查询二级行业
            QueryWrapper secondQw = new QueryWrapper();
            secondQw.eq("level", LevelEnum.LEVEL_1.getCode());
            secondQw.eq("trade_id", item.getId());
            secondQw.orderByAsc("id");


            List<PfCategorySub> subList = pfCategorySubMapper.selectList(secondQw);
            List<CategoryRightFirstVo> rightFirstVos = new ArrayList<>();

            for (PfCategorySub subItem : subList) {
                CategoryRightFirstVo firstVo = new CategoryRightFirstVo();
                firstVo.setCategoryId(subItem.getTradeId());
                firstVo.setId(subItem.getId());
                firstVo.setName(subItem.getSubName());

                // 查询三级行业
                QueryWrapper thirdQw = new QueryWrapper();
                thirdQw.eq("level", LevelEnum.LEVEL_2.getCode());
                thirdQw.eq("trade_id", item.getId());
                thirdQw.eq("parent_id", subItem.getId());
                thirdQw.orderByAsc("id");
                List<PfCategorySub> thirdList = pfCategorySubMapper.selectList(thirdQw);
                List<CategoryRightSecondVo> rightSecondVos = new ArrayList<>();
                for (PfCategorySub thirdItem : thirdList) {
                    CategoryRightSecondVo secondVo = new CategoryRightSecondVo();
                    secondVo.setCategoryId(thirdItem.getTradeId());
                    secondVo.setId(thirdItem.getId());
                    secondVo.setName(thirdItem.getSubName());
                    secondVo.setParentId(thirdItem.getParentId());
                    secondVo.setPath(Const.HTTPS + thirdItem.getPath());
                    rightSecondVos.add(secondVo);
                    firstVo.setCategoryRightSecondVos(rightSecondVos);
                }
                rightFirstVos.add(firstVo);
            }
            rtnList.add(rightFirstVos);
            rightFirstVos = new ArrayList<>();
        });
        return rtnList;
    }

    /**
     * 查询子行业中所有一级行业
     *
     * @param idDto 存放当前行业的主键id
     */
    @Override
    public List<ParentCategoryVo> queryParentCategoryVo(IdDto idDto) {
        Long id = idDto.getId();

        QueryWrapper<PfCategorySub> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("trade_id", id);
        queryWrapper.eq("level", LevelEnum.LEVEL_1.getCode());
        queryWrapper.orderByDesc("id");


        List<PfCategorySub> pfCategorySubs = pfCategorySubMapper.selectList(queryWrapper);

        List<ParentCategoryVo> rtnList = new ArrayList<>();
        pfCategorySubs.forEach(item -> {
            ParentCategoryVo parentCategoryVo = new ParentCategoryVo();
            BeanUtil.copyProperties(item, parentCategoryVo);
            parentCategoryVo.setName(item.getSubName());
            rtnList.add(parentCategoryVo);
        });
        return rtnList;
    }

    /**
     * 查询行业列表是否展示
     */
    @Override
    public String isDisplayCategoryList() {
        List<CategoryDisplay> categoryDisplays = categoryDisplayMapper.selectList(new QueryWrapper<>());
        if(!categoryDisplays.isEmpty()){
            CategoryDisplay categoryDisplay = categoryDisplays.get(0);
            Integer type = categoryDisplay.getType();
            return type + "";
        } else {
            return "1";
        }
    }
}
